/**
* 新增供货商维权处理弹框：换货 Add by 2015-1-15
*/
<template>
    <kdx-modal-frame
        v-model="value"
        title="维权处理"
        :width="700"
        @on-cancel="handleCancel"
        @on-ok="handleOk"
    >
        <Form
            ref="form"
            :label-width="120"
            :model="model"
            class="order-refund-detail-refund-modal"
            :rules="rules"
        >
            <FormItem label="维权类型：" class="r-form-item-text">
                <kdx-tag-label type="danger" size="small">换货</kdx-tag-label>
              <!--  供货商维权状态-->
              <p v-if="isJST && data.refund_info.supplier_status" class="alert-blue">
                供货商维权状态：{{ data.refund_info.supplier_status }}
              </p>
            </FormItem>
            <FormItem
                label="处理方式："
                class="r-form-item-checkbox"
                porp="type"
            >
                <RadioGroup v-model="model.type">
                    <Radio label="0" v-if="status === 0">驳回申请</Radio>
                    <Radio label="1" v-if="status === 0">通过申请</Radio>
                    <Radio label="2" v-if="(status < 3 && !isJST) || (status < 3 && isJST && model.type === '2')">确认发货</Radio>
                    <Radio label="3" v-if="status === 3">
                        关闭申请（确认换货完成）
                    </Radio>
                </RadioGroup>
                <kdx-hint-alert
                    :show-icon="false"
                    type="info"
                    v-show="model.type === '1'"
                >
                    通过申请后需要收到客户寄回商品才可进行下一步操作
                </kdx-hint-alert>
                <kdx-hint-alert
                    :show-icon="false"
                    type="info"
                    v-show="model.type === '2' && status < 2 && !isJST"
                >
                    无需客户寄回商品，商家直接发换货商品
                </kdx-hint-alert>
            </FormItem>
            <FormItem
                label="驳回原因："
                v-show="model.type === '0'"
                porp="reason"
            >
                <Input
                    type="textarea"
                    class="width-430"
                    placeholder="请输入"
                    autosize
                    :maxlength="200"
                    v-model="model.reason"
                />
            </FormItem>
            <FormItem
                label="退货地址："
                prop="address"
                v-if="model.type === '1'"
            >
                <Select class="width-430" v-model="model.address">
                    <Option
                        :label="address.title"
                        :value="address.id"
                        v-for="address in address.list"
                        :key="address.id"
                    ></Option>
                </Select>
            </FormItem>
            <!-- <FormItem label="留言：" v-show="model.type === '1'" prop="message">
                <Input
                    v-model="model.message"
                    type="textarea"
                    autosize
                    :maxlength="200"
                    class="width-430"
                    placeholder="请输入"
                />
            </FormItem> -->
            <FormItem
                label="选择快递公司："
                prop="express_com"
                v-if="model.type === '2'"
            >
                <select-express
                    class="width-340"
                    :value.sync="model.express_com"
                    :option-data="express.list"
                ></select-express>
            </FormItem>
            <FormItem
                label="快递单号："
                v-if="model.type === '2'"
                prop="express_sn"
            >
                <i-input
                    class="width-340"
                    placeholder="请输入"
                    v-model="model.express_sn"
                />
            </FormItem>

          <!--    聚水潭商品订单：需要创建供货商维权售后单 -->
          <div class="content" v-show="isJST && model.type == '1'">
          <div class="title">
              供货商维权售后处理
              <kdx-tag-label type="danger" size="small">申请金额和退换货请提前确认</kdx-tag-label>
            </div>
            <FormItem label="应退金额：">
              <kdx-rr-input v-model="model.supplier_refund_price" number :fixed="2" :minValue="0" :maxValue="9999999.99" class="width-160"
                            @on-blur="changeSupplierRefund">
                <span slot="append">元</span>
              </kdx-rr-input>
            </FormItem>
            <FormItem label="应补金额：">
              <kdx-rr-input v-model="model.supplier_payment_price" number :fixed="2" :minValue="0" :maxValue="9999999.99" class="width-160"
                            @on-blur="changeSupplierPayment">
                <span slot="append">元</span>
              </kdx-rr-input>
            </FormItem>
            <div class="label" v-for="(item) in model.return_good_info" :key="item.goods_id">
              <kdx-tag-label type="danger" size="small">退</kdx-tag-label>
              商品：{{item.title}}，参考单成本：<span class="price"> ￥{{item.single_cost_price}}</span>
              ，参考成本小计：￥{{parseFloat(item.single_cost_price).toFixed(2) * parseInt(item.total)}}
              <FormItem
                  label="退货数：" prop="total">
                <i-input
                    class="width-100"
                    placeholder="请输入退货数"
                    v-model="item.total"/>
              </FormItem>
            </div>
            <!--                选择更换商品：-->
            <div class="label" >
              <Button class="default-primary" @click="addShop">+选择更换商品</Button>
              <kdx-tag-label type="danger" size="small">请确认换货商品为同供货商下同品牌商品</kdx-tag-label>
            </div>
            <div class="label" v-show="shop.data && shop.data.length > 0" v-for="(item) in model.barter_good_info" :key="item.goods_id">
              <kdx-tag-label type="danger" size="small">换</kdx-tag-label>
<!--              商品：{{item.title}}，参考单成本：<span class="price"> ￥{{item.cost_price}}</span>-->
              商品：{{item.title}}，参考单成本：<span class="price"> ￥{{item.single_cost_price}}</span>
              ，参考成本小计：￥{{parseFloat(item.single_cost_price).toFixed(2) * parseInt(item.total)}}
              <FormItem
                  label="换货数：" prop="total">
                <i-input
                    class="width-100"
                    placeholder="请输入换货数"
                    v-model="item.total"/>
              </FormItem>
            </div>

          </div>
        </Form>
      <!--商品选择器-->
      <goods-selector
          v-model="selector.value"
          :multiple="true"
          :current-list="selector.data"
          @on-change="selectorChange"
          @on-cancel="selectorCancel"></goods-selector>
    </kdx-modal-frame>
</template>

<script>
import SelectExpress from '../../../components/SelectExpress'
import GoodsSelector from "@/components/selector/GoodsSelector.vue";

export default {
    name: 'RefundModalNew',
    components: {GoodsSelector, SelectExpress },
    props: {
        visible: {
            type: Number,
            default: 0,
        },
        data: {
            type: Object,
            default: () => {},
        },
        // 维权状态
        status: {
            type: Number,
            default: 0,
        },
    },
    data() {
        return {
          selector: {
            value: false,
            data: []
          },
          shop: {
            columns: [
              {
                title: '商品',
                key: 'shop',
                minWidth: 200,
              },
              {
                title: '单成本价',
                key: 'cost_price',
                minWidth: 80,
                render: (h, params) => {
                  // 多规格
                  if (params.row.has_option === '1') {
                    return (
                        <div class="cost_price">
                          <span>￥{params.row.min_price} ~ ￥{params.row.max_price}</span>
                        </div>
                    );
                  }
                  return (
                      <div class="cost_price">
                        <span>￥{params.row[params.column.key]}</span>
                      </div>
                  );
                }
              },
              {
                title: '库存',
                key: 'stock',
                minWidth: 80,
                render: (h, params) => {
                  let stock = params.row[params.column.key]
                  return (
                      <div class="inventory">
                        <span>{stock}</span>
                      </div>
                  );
                }
              }
            ],
            data: [],
            total: 0
          },
          page: {
            pageSize: 10,
            pageNumber: 1, // 页码
          },
            value: false,
            model: {
                type: '0',
                // message: '',
                address: '',
                express_com: '',
                express_sn: '',
                dispatch_type: '30',
                supplier_refund_price: 0,
                supplier_payment_price: 0,
                return_good_info: [{
                  title: "",
                  total: "",
                  price: "",
                  supplierCode: "",
                  single_cost_price: "",
                  old_total: "",
                }],
                barter_good_info:[{
                  title: "",
                  total: "",
                  price: "",
                  supplierCode: "",
                  single_cost_price: "",
                }],
            },
            address: {
                list: [],
            },
            express: {
                list: [],
            },
            rules: {
                address: [{ required: true, message: '请选择退货地址' }],
                express_com: [{ required: true, message: '请选择快递公司' }],
                express_sn: [
                    {
                        required: true,
                        message: '请输快递单号',
                        trigger: 'blur',
                    },
                ],
                dispatch_type: [{ required: true, message: '配送方式必选' }],
            },
        }
    },
    watch: {
        visible() {
            this.value = true
            this.getAddress()
            this.getExpress()
        },
        status: {
            handler(val) {
                if (val == 1 || val == 2) {
                    this.model.type = '2'
                } else if (val == 3) {
                    this.model.type = '3'
                }
            },
            immediate: true,
        },
    },
  created() {
    let return_good_info = [];
    for (let orderGood of this.data.orderGoods) {
      let goodInfo = this.data.goods_info.find((item) => {
        return orderGood.goods_id == item.goods_id
      })

      let orderGoodInfo = {
        supplierCode: goodInfo.supplierGoodId,
        title: goodInfo.title,
        total: orderGood.total,
        price: orderGood.cost_price,
        single_cost_price:  parseFloat(goodInfo.cost_price).toFixed(2) / parseInt(goodInfo.total),
        old_total: orderGood.total,
      }
      return_good_info.push(orderGoodInfo);
    }
    this.model.return_good_info = return_good_info;
    // console.log('return_good_info------11111', this.model.return_good_info)
  },
    methods: {
      isJST() {
        return (this.data.refund_info && this.data.refund_info.supplier == 'jushuitan') ? true : false;
      },
      // 供货商维权售后处理金额
      changeSupplierRefund() {
        this.$nextTick(() => {
          if (parseFloat(this.model.supplier_refund_price) && parseFloat(this.model.supplier_refund_price) > 0) {
            this.model.supplier_refund_price = parseFloat(this.model.supplier_refund_price).toFixed(2);
          } else {
            this.model.supplier_refund_price = '0';
            this.$set(this.model, 'supplier_refund_price', '0');
          }
        })
      },
      changeSupplierPayment() {
        this.$nextTick(() => {
          if (parseFloat(this.model.supplier_payment_price) && parseFloat(this.model.supplier_payment_price) >= 0) {
            this.model.supplier_payment_price = parseFloat(this.model.supplier_payment_price).toFixed(2);
          } else {
            this.model.supplier_payment_price = '0';
            this.$set(this.model, 'supplier_payment_price', '0');
          }
        })
      },
      addShop() {
        this.selector.value = true
      },
      selectorChange(list) {
        this.selector.data = list
        this.model.goods_id = list.map(item => item.id)
        this.resetPage()
        this.getPageShopData()
        this.selectorCancel()
        // console.log('this.selector.data------', list)

        // 换货数据
        let barter_good_info = [];
        for (let good of list) {
          let goodInfo = {
            supplierCode: good.supplierGoodId,
            title: good.title,
            total: good.total,
            single_cost_price: good.cost_price,
          }
          goodInfo.price = parseFloat(goodInfo.single_cost_price).toFixed(2) * parseInt(goodInfo.total);
          barter_good_info.push(goodInfo);
          // console.log('barter_good------', good)
          if (good.supplier != this.data.refund_info.supplier) {
            return this.$Message.error('请选择同供货商下同品牌的商品换货！');
          }
        }
        this.model.barter_good_info = barter_good_info;
        // console.log('barter_good_info------11111', barter_good_info)
      },
      selectorCancel() {
        this.selector.value = false
      },
      // 重置页码信息
      resetPage() {
        this.page.pageSize = 10
        this.page.pageNumber = 1
      },
      filteredGoods(goods) {
        // 使用 filter 方法筛选商品
        return goods.filter(good => good.supplier == this.data.refund_info.supplier && good.supplierType == this.data.refund_info.supplierType)
      },
      // 获取当前显示的商品
      getPageShopData() {
        this.shop.total = this.selector.data.length
        let start = this.page.pageSize * (this.page.pageNumber - 1),
            end = this.page.pageSize * this.page.pageNumber
        this.shop.data = this.selector.data.slice(start, end)
      },
        getAddress() {
            if (this.address.list.length) {
                return
            }
            this.$api.settingApi.getAllRefundAddress().then((res) => {
                if (res.error === 0) {
                    this.address.list = res.list
                }
            })
        },
        getExpress() {
            if (this.express.list.length) {
                return
            }

            this.$api.settingApi.getExpressList().then((res) => {
                if (res.error === 0) {
                    this.express.list = res.list
                }
            })
        },
        handleCancel() {
            this.value = false
            this.$refs.form.resetFields()
        },
        handleOk() {
            let type = this.model.type
            let {
                id,
                refund_type,
                refund_info: { order_goods_id },
            } = this.data

            let data = {
                order_id: id,
            }

            if (refund_type == '2') {
                data.order_goods_id = order_goods_id
            }

          // this.handleSupplierRefundGood(1, data);

            if (type === '0') {
                this.rejectHandler(data)
            } else if (type === '1') {
                data = this.handleSupplierRefundGood(data);

                this.agreeHandler(data)
            } else if (type === '2') {
                this.sureHandler(data)
            } else {
                this.closeHandler(data)
            }
        },
        closeHandler(data) {// 关闭申请，确认换货成功
            this.$api.orderApi
                .exchangeClose(data)
                .then((res) => {
                    if (res.error === 0) {
                        this.$Message.success('操作成功')
                        this.$parent.$parent.getData()
                    } else {
                      this.$Message.error('处理申请失败')
                    }
                })
                .finally(() => {
                    this.value = false
                })
        },
        sureHandler(data) {// 换货商家发出货物
            this.$refs.form.validate((valid) => {
                if (valid) {
                    let { code, name, key } = this.express.list.filter(
                        (list) => list.id === this.model.express_com
                    )[0]
                    data = Object.assign(data, {
                        seller_express_sn: this.model.express_sn,
                        seller_express_name: name,
                        seller_express_code: code,
                        seller_express_encoding: key,
                    })
                    this.$api.orderApi
                        .exchangeSend(data)
                        .then((res) => {
                            if (res.error === 0) {
                                this.$Message.success('操作成功')
                                this.$parent.$parent.getData()
                            } else {
                              this.$Message.error('处理申请失败')
                            }
                        })
                        .finally(() => {
                            this.value = false
                        })
                }
            })
        },
        agreeHandler(data) { // 退货通过申请
            data.refund_address_id = this.model.address

            if (this.model.message) {
              data.seller_message = this.model.message
            }

            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.$api.orderApi
                        .agreeReturn(data)
                        .then((res) => {
                            if (res.error === 0) {
                                this.$Message.success('操作成功')
                                this.$parent.$parent.getData()
                            } else {
                              this.$Message.error('处理申请失败')
                            }
                        })
                        .finally(() => {
                            this.value = false
                        })
                }
            })
        },
        autoHandler(data) {
            this.$api.orderApi
                .autoRefund(data)
                .then((res) => {
                    if (res.error === 0) {
                        this.$Message.success('操作成功')
                        this.$parent.$parent.getData()
                    }
                })
                .finally(() => {
                    this.value = false
                })
        },
        manualHandler(data) {
            this.$api.orderApi
                .manualRefund(data)
                .then((res) => {
                    if (res.error === 0) {
                        this.$Message.success('操作成功')
                        this.$parent.$parent.getData()
                    }
                })
                .finally(() => {
                    this.value = false
                })
        },
        rejectHandler(data) {// 驳回申请
            if (this.model.reason) {
                data.reject_reason = this.model.reason
            }
            this.$api.orderApi
                .refundRejectOrder(data)
                .then((res) => {
                    if (res.error === 0) {
                        this.$Message.success('操作成功')
                        this.$parent.$parent.getData()
                    }
                })
                .finally(() => {
                    this.value = false
                })
        },

      // 供货商维权售后处理数据
      handleSupplierRefundGood(data) {
        if (this.data.refund_info.supplier && this.data.refund_info.supplier == 'jushuitan') {
          for (const item of this.model.return_good_info) {
            item.price = parseFloat(item.single_cost_price).toFixed(2) * parseInt(item.total);
            if (parseInt(item.total) > parseInt(item.old_total)) {
              return this.$Message.error('申请退货数量不可大于所买数量');
            }
            if (parseInt(item.total) <= 0) {
              return this.$Message.error('申请退货数量不可为0');
            }
            delete item.single_cost_price;
            delete item.old_total;
          }
          // console.log('return_good_info------11111', this.model.return_good_info)
          for (const item of this.model.barter_good_info) {
            item.price = parseFloat(item.single_cost_price).toFixed(2) * parseInt(item.total);
            if (parseInt(item.total) <= 0) {
              return this.$Message.error('申请换货数量不可为0');
            }
            delete item.single_cost_price;
          }
          // console.log('barter_good_info------11111', this.model.barter_good_info)
          let refundData = {
            order_id: parseInt(this.data.refund_info.order_id),
            refund_type: this.data.refund_info.refund_type,
            refund_no: this.data.refund_info.refund_no,
            order_goods_id: parseInt(this.data.refund_info.order_goods_id),
            price: this.model.supplier_refund_price,
            reason: this.data.refund_info.content,
            supplier: this.data.refund_info.supplier,
            supplierType: this.data.refund_info.supplierType ? this.data.refund_info.supplierType : '',
            return_good_info: this.model.return_good_info,
            barter_good_info: this.model.barter_good_info,
          }
          if (this.model.supplier_payment_price > 0) {
            refundData.supplier_payment_price = this.model.supplier_payment_price;
          }
          data.supplier_refund_info = refundData;
          // console.log('return_good_info------data--', data)
        }
        return  data;
      },
    },
}
</script>

<style scoped lang="scss">
.order-refund-detail-refund-modal {
    padding: 30px 20px 20px 0;
    .ivu-form-item {
        margin-bottom: 20px;
        .hint-alert-component {
            margin-top: 10px;
            p {
                @include font-12-24;
            }
        }
    }
    ::v-deep .ivu-form-item-label {
        padding-right: 0;
    }

  .content {
    .title {
      @include font-16-22-bold;
      color: $text-first;
      padding: 10px;
    }
    .text {
      @include font-14-20-bold;
      padding: 10px 10px;
    }
    > .label {
      margin-left: 10px;

      > .price {
        @include font-14-20-bold;
        color: $danger-color;
      }
    }
    .ivu-form-item {
      margin-bottom: 9px !important;
    }
  }
}
</style>
